﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace tdtools
{
    class Program
    {
        static void Main(string[] args)
        {
            DownUtil.DownRequest Request = new DownUtil.DownRequest();
            Request.Url = "ftp://releases.mozilla.org/pub/mozilla.org/firefox/releases/3.5.1/win32/zh-CN/Firefox%20Setup%203.5.1.exe";
            Request.UserNAme = "Alex";
            Request.Password = "123";

            //Uri uri = new Uri(Request.Url);

            TcpClient client = new TcpClient();
                  
            try
            {
                client.Connect(
                                    new IPEndPoint(
                    IPAddress.Parse("125.64.94.211"),
                    21
                    )
                    );
                NetworkStream Ns = client.GetStream();
                byte[] requestdata = Request.Serialize();
                Ns.Write(requestdata, 0, requestdata.Length);
                Ns.Flush();
                Console.WriteLine("Request File - " + Request.Url);

                if (Ns.ReadByte() > 0)
                {
                    Console.WriteLine("Authenticate False");
                }
                else
                {
                    if (Ns.ReadByte() > 0)
                    {
                        Console.WriteLine("Remote Access False");
                    }
                    else
                    {
                        using (FileStream fils = new FileStream("d:\\firefoxsetup.exe",FileMode.OpenOrCreate))
                        {
                            byte[] buffer = new byte[2048];
                            int ReadCount = 0;
                            while ((ReadCount = Ns.Read(buffer, 0, 2048)) > 0)
                            {
                                Console.WriteLine("one block transfered " + ReadCount + " Byte");
                                fils.Write(buffer, 0, ReadCount);
                            }
                            Ns.Close();
                            Console.WriteLine("Transfer done");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("error", ex);
            }
            finally
            {
                client.Close();
            }
            Console.Read();
        }
    }
}
